<template>
  <div class="login-container">
    <van-nav-bar title="登录">
      <template #left>
        <img class="logo" src="@/assets/images/logo.png"/>
      </template>
    </van-nav-bar>
    <!-- // 下方表单验证项内容哈 -->
<van-form @submit="onSubmit">
      <van-field
        v-model="loginForm.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[{ required: true, message: '请填写手机号', trigger: 'onChange', pattern: /^1[3-9]\d{9}$/  }]"
      />
      <van-field
        v-model="loginForm.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[{ required: true, message: '请填写密码', trigger: 'onChange', pattern: /^\d{6}$/ }]"
      />
      <div style="margin: 16px;">
        <!-- loading 为了防止用户在 网慢的情况下疯狂的点击哈 俩个布尔值 loading-text  -->
        <van-button block type="info" native-type="submit" :loading="isLoading" loading-text="拼命加载中...">登录</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
// 使用mutations 映射到个人用户的模块块,
import { setRefreshToken, setToken } from '@/utils/token'
import { LoginApi } from '@/api/Login'
export default {
  name: 'Login',
  data () {
    return {
      isLoading: false,
      loginForm: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      }
    }
  },
  methods: {
    async  onSubmit () {
      try {
        // 点击的时候设置为true
        this.isLoading = true
        const res = await LoginApi(this.loginForm)
        const { refresh_token, token } = res.data
        //  拿到对应 toeken 值给到共享的数据中
        setToken(token)
        setRefreshToken(refresh_token)
        this.$notify({ type: 'success', message: '登录成功' })
        // replace 路由跳转过去是无法回退的
        this.$router.replace(this.$route.query.form || '/')
      } catch (e) {
        this.$notify({ type: 'warning', message: '登录失败' })
      } finally { // 无论代码成功还是失败都会执行到这
        // 加载完成就设置为false
        this.isLoading = false
      }
    }
  }
}
</script>
<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
.van-nav-bar {
   background: #007bff;
   /* /deep/ 就是把data-v-hash值选择器写到类名的前面 */
/deep/ .van-nav-bar__title{
  color: white;
}
}

</style>
